package rollercoaster.train.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import rollercoaster.commons.Vertex3D;
import rollercoaster.train.interfaces.ISurfaceControlPointsReader;

public class OBJControlPointsSingleSurfaceReader implements ISurfaceControlPointsReader {
	
	private String filepath;

	public OBJControlPointsSingleSurfaceReader(String filepath) {
		super();
		this.filepath = filepath;
	}

	public Vertex3D[][] getControlPoints(String filepath) {
		this.filepath = filepath;
		return getControlPoints();
	}
	
	public Vertex3D[][] getControlPoints(){
		int dim_u=0;
		int dim_v=0;
		List<Vertex3D> vertices= new ArrayList<Vertex3D>();
		
		try {	
			BufferedReader reader = new BufferedReader(new FileReader(new File(filepath)));
			String s;
			try {
				while((s = reader.readLine()) != null){
					StringTokenizer tok=new StringTokenizer(s," ");
					if(s.startsWith("v ")){
						tok.nextToken();
						Vertex3D vertex=new Vertex3D(Float.parseFloat(tok.nextToken()), Float.parseFloat(tok.nextToken()), Float.parseFloat(tok.nextToken()));
						vertices.add(vertex);
					}
					if(s.startsWith("parm u")){
						int dim_knot_u=tok.countTokens()-2;
						dim_u=dim_knot_u-3;
					}
					if(s.startsWith("parm v")){
						int dim_knot_v=tok.countTokens()-2;
						dim_v=dim_knot_v-3;
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Vertex3D[][] controlPoints = new Vertex3D[dim_v][dim_u];
		int k=0;
		for (int i = 0; i < dim_v; i++) {
			for (int j = 0; j < dim_u; j++) {
				controlPoints[i][j]=vertices.get(k);
				k++;
			}
		}
		
		return controlPoints;
		
	}

}
